package br.com.bolsamovel;

import org.droidsql.DBHelpper;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class AccountsActivity extends Activity {

	private SimpleCursorAdapter adp;
	private ListView lstAccount;
	private Button btnNewAccount;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.accounts);
		
		lstAccount = (ListView) findViewById(R.id.accounts_listView);
		btnNewAccount = (Button) findViewById(R.id.accounts_btnNew);
		
		btnNewAccount.setOnClickListener(new View.OnClickListener(){
			public void onClick(View v) {
				newAccount();
			}});

		adp = new SimpleCursorAdapter(this,R.layout.lst_account_layout,null,new String[]{"_id","name"} , new int[]{R.id._id,R.id.name});

		lstAccount.setAdapter(adp);
		
		lstAccount.setOnItemClickListener(new OnItemClickListener(){
			public void onItemClick(AdapterView<?> av, View v, int pos,	long id) {
				Intent i = new Intent(AccountsActivity.this, AccountEditActivity.class);
				i.putExtra("rec_id", id);
				startActivity(i);
			}});
		
	}

	@Override
	protected void onResume() {
		super.onResume();
		onShow();
	}
	
	private void onShow(){
		try{
			Cursor c = DBHelpper.getInstance().getConnection().rawQuery("select _id,name from accounts", null);
			
			adp.changeCursor(c);
			
			if(AccountUtils.hasAnyAccount()){
				lstAccount.setVisibility(View.VISIBLE);
				btnNewAccount.setVisibility(View.INVISIBLE);
			}else{
				lstAccount.setVisibility(View.INVISIBLE);
				btnNewAccount.setVisibility(View.VISIBLE);
			}
		}catch (Exception e) {
			UIUtils.throwsNonChecked(e);
		}
	}
	
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.accounts_menu, menu);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.new_account:
			newAccount();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void newAccount() {
		Intent i = new Intent(this, AccountEditActivity.class);
		i.putExtra("isnew", Boolean.TRUE);
		startActivity(i);
	}
}